#coding=utf-8
'''
Created on 2016年6月7日

@author: 404039

********************************************************
1.通过COM口连接平台
2.运行该函数先配置configure文件配置port，baudrate，进入cli的命令与密码
3.当串口已经打开后，再次输入打开串口命令会关闭串口，此时应该再次打开
4.当超过规定时间还没打开串口时，打开失败，重新运行

********************************************************
'''

import ConfigParser
import datetime
import os
import time
import serial
import ConfigParser
import re
import serial  
import logging_save
import sys
sys.path.append('D:\eclipse\luyouqi\src')
import config

def Connection():
    Conf = ConfigParser.ConfigParser()
    #读配置文件
    with open('D:\eclipse\luyouqi\src\common\configuration.txt','r') as f:
        Conf.readfp(f)

        Conn = serial.Serial(config.choose_port(),config.GetBaudRate(),bytesize=8)
        #建立串口连接
        time.sleep(1)
        CliCommand = Conf.get('EnterCliCommand','Key')
        #打开串口命令
        CliPassword = Conf.get('EnterCliPassword','Key')
        #打开串口密码
        Conn.write(CliCommand+'\n')
        #time.sleep(1)
        Conn.write(CliPassword+'\n')
        #time.sleep(1)
        key1 = 'CLI is OFF'
        key2 = 'CLI is ON'
        StartTime = datetime.datetime.now()
        #times = 0
        while 1:
            EndTime = datetime.datetime.now()
            conntime = (EndTime - StartTime).seconds
            #获取当前循环时间
            Date = Conn.readline()
            #print Date
            if key2 in Date:
                #打开串口成功
                #print 'ok'
                return Conn
                #Conn.close()
                print '1'
                #print 'ok2'
                #break
            elif  key1 in Date:
                #当输入打开串口命令后有可能会把串口关闭，如，如果已经打开了，再次输入会关闭串口，当关闭后需重新输入命令打开
                #print 'ok00000000'
                Conn.write(CliCommand+'\n')
                Conn.write(CliPassword+'\n')
                time.sleep(1)
                #Conn.close()

            elif conntime > 20:
                #当超过20秒后打开串口失败，需重新打开
                print 'conn timeout,conn again!'
                break
                #Conn.close()
                print '3'
                

        
#Connection()